package com.fulihui.wgj.consumer.communication.normal;

import com.fulihui.common.enums.MsgTypeEnum;
import com.fulihui.open.weixin.enums.IsTdEnum;
import com.fulihui.wgj.consumer.service.UserService;
import com.fulihui.wgj.consumer.service.WxMsgService;
import com.fulihui.wgj.facade.dto.WxUserInfoDTO;
import com.fulihui.wgj.facade.msg.EventMsg;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Collections;

/**
 * @author: LiuJie
 * @version: 2018/7/20 15:13
 * @description:
 */
@Component
public class TextProcessor implements NormalMsgProcessor {
    @Autowired
    private UserService userService;
    @Autowired
    private WxMsgService wxMsgService;
    /**
     * 事件消息处理
     *
     * @param message 消息模型
     */
    @Override
    public void process(EventMsg message) {
        String content = message.getContent();
        if (StringUtils.isBlank(content)) {
            return;
        }
        String appId = message.getAppId();
        String openId = message.getFromUserName();

        /**
         * TD 退订逻辑<br>
         */
        WxUserInfoDTO dto = new WxUserInfoDTO();
        dto.setAppId(appId);
        dto.setOpenid(openId);
        if (content.equalsIgnoreCase("td") || content.equals("退订")) {
            // 更新用户退订标记-退订
            dto.setIsTd(IsTdEnum.IS.getValue());
            userService.upsertUsers(Collections.singletonList(dto));
            wxMsgService.sendCustomerTextMsg(appId,openId,"退订成功！感谢您一直以来的支持！订阅回复\"dy\"或\"订阅\"即可哦 ^_^");
            LOGGER.info("用户退订，appid = {} ,openid = {}",appId,openId);
        }
        if (content.equalsIgnoreCase("dy") || content.equals("订阅")) {
            // 更新用户退订标记-不退订
            dto.setIsTd(IsTdEnum.NOT.getValue());
            userService.upsertUsers(Collections.singletonList(dto));
            wxMsgService.sendCustomerTextMsg(appId,openId,"订阅成功！感谢您的关注！退敌回复\"td\"或\"退订\"即可哦 ^_^");
            LOGGER.info("用户订阅，appid = {} ,openid = {}",appId,openId);
        }
    }

    /**
     * 消息类型, 用于注册到处理器集合中, 业务方法通过对应event获取到该处理器
     *
     * @return 类型字符串
     * @see MsgTypeEnum
     */
    @Override
    public String getEvent() {
        return MsgTypeEnum.text.getCode();
    }
}
